<?php

namespace app\libs\orm;

use \wicked\tools\Inflector;

abstract class Record
{

    /**
     * @param array $data
     * @param null $null
     */
    public function __construct(array $data = [], $null = null)
    {
        $this->set($data);
    }

    /**
     * @param array $set
     */
    public function set(array $set)
    {
        foreach ($set as $field => $value)
            $this->{$field} = $value;
    }

    protected  function preSave(){}
    protected function postSave(){}

    /**
     * @return bool
     */
    public function save()
    {
        $refs = (new \ReflectionObject($this))->getProperties(\ReflectionProperty::IS_PUBLIC);
        foreach ($refs as $ref) $vars[$ref->name] = $this->{$ref->name};

        if (empty($this->{SimpleORM::convention('primary')}))
        {
            $values = array_fill(0, count($vars), '?');
            $sql = 'INSERT INTO `' . static::table() . '` (`' . implode('`,` ', array_keys($vars)) . '` VALUE (' . implode(', ', $values) . '))';
        }
        else {
            $sql = 'UPDATE `' . static::table() . '` SET ';
            $set = [];
            foreach ($vars as $field => $value)
                $set[] = '`' . $field . '` = ?';
            $sql .= implode(', ', $set) . ' WHERE `' . SimpleORM::convention('primary') . '` = ' . $this->{SimpleORM::convention('primary')};
        }
        $stm = SimpleORM::pdo()->prepare($sql);
        $result = $stm->execute(array_values($vars));

        return $result;
    }

    /**
     * @return int
     */
    public function delete()
    {
        $sql = 'DELETE FROM `' . static::table() . '` WHERE `' . SimpleORM::convention('primary') . '` = ' . $this->{SimpleORM::convention('primary')};
        return SimpleORM::pdo()->exec($sql);
    }

    /**
     * @static
     * @return string
     */
    static protected function table()
    {
        return Inflector::tablename(get_called_class());
    }

}
